package com.zhiwei.popup

import android.content.Context
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.ImageView
import android.widget.ListAdapter
import android.widget.Toast
import com.squareup.picasso.Picasso

class ImageActivity : AppCompatActivity() {

    var images: Array<String>? = null


    private val recyclerView: RecyclerView?
        get() {
            val recyclerView = findViewById<RecyclerView>(R.id.imageList)
            return recyclerView
        }
    private val swipeRefresh: SwipeRefreshLayout?
        get(){
            val swipe = findViewById<SwipeRefreshLayout>(R.id.swipeRefresh)
            return swipe
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image)

        images = this.assets.list("image")

        println("images $images")

        val lm: RecyclerView.LayoutManager = GridLayoutManager(this, 3)
        recyclerView?.layoutManager = lm
        recyclerView?.addItemDecoration(RecyclerViewItemDecoration(RecyclerViewItemDecoration.MODE_GRID, "#EBEBEB", 2, 0, 0))
        val adapter = ImageAdapter(this, images)
        recyclerView?.adapter = adapter

        swipeRefresh?.setOnRefreshListener {
            Toast.makeText(baseContext, "wahaha", Toast.LENGTH_SHORT).show()

//            Thread().run{
//                Thread.sleep(3000)
//                runOnUiThread{
//                    swipeRefresh?.isRefreshing = false
//                }
//            }
        }
    }

    class ImageAdapter(internal var context: Context, internal var images: Array<String>?) : RecyclerView.Adapter<ImageViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ImageViewHolder {
            val view = LayoutInflater.from(context).inflate(R.layout.image, parent, false)
            return ImageViewHolder(view)
        }

        override fun getItemCount(): Int = images!!.size

        override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
            val imageUrl = "file:///android_asset/image/"
            var str = images?.get(position)
            str = imageUrl + str
            println("load image $str")

            val imageView = holder.itemView.findViewById<ImageView>(R.id.image)
            imageView.setBackgroundColor(Color.RED)
            Picasso.with(context)
                    .load(str)
                    .placeholder(R.mipmap.ic_launcher)
                    .into(imageView)
        }

    }

    class ImageViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)
}
